<!--
 * @Author: DUST
 * @Date: 2023-11-25 23:59:25
 * @LastEditors: DUST
 * @LastEditTime: 2024-11-11 15:28:03
 * @FilePath: \business-card-system\admin\src\views\admin\companyInfo\index.vue
 * @Description: 
 * undefined
-->
<template>
  <admin-page-template>
    <div class="companyInfo">
      <a-form
        ref="formref"
        :model="formModel"
        class="ModalForm"
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 20 }"
      >
        <a-form-item
          label="公司名称"
          name="name"
          :rules="[{ required: true, message: '公司名称不能为空' }]"
        >
          <a-input
            placeholder="请输入公司名称"
            v-model:value="formModel.name"
          />
        </a-form-item>
        <a-form-item label="公司简称1" name="desName">
          <a-input
            placeholder="请输入公司简称1"
            v-model:value="formModel.desName"
          />
        </a-form-item>
        <a-form-item label="公司简称2" name="desName1">
          <a-input
            placeholder="请输入公司简称2"
            v-model:value="formModel.desName1"
          />
        </a-form-item>
        <a-form-item label="公司简称3" name="desName3">
          <a-input
            placeholder="请输入公司简称3"
            v-model:value="formModel.desName3"
          />
        </a-form-item>
        <a-form-item
          label="办公地址1"
          name="addr"
          :rules="[{ required: true, message: '公司地址不能为空' }]"
        >
          <a-input
            placeholder="请输入公司地址"
            v-model:value="formModel.addr"
          />
        </a-form-item>
        <a-form-item
          label="办公地址2"
          name="addr2"
          :rules="[{ required: true, message: '公司地址不能为空' }]"
        >
          <a-input
            placeholder="请输入公司地址"
            v-model:value="formModel.addr2"
          />
        </a-form-item>
        <a-form-item label="公司位置">
          <tenMap
            @selectPosition="selectPosition"
            :lng="formModel.lng"
            :lat="formModel.lat"
          />
          <!-- <div class="mapBox"></div> -->
        </a-form-item>
        <a-form-item label="简介图片" name="imgs">
          <a-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :before-upload="beforeUpload"
            @preview="handlePreview"
            @remove="removeFile"
          >
            <div v-if="fileList.length < 6">
              <plus-outlined />
              <div style="margin-top: 8px">简介图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="轮播图片" name="swipperFiles">
          <a-upload
            v-model:file-list="swippersList"
            list-type="picture-card"
            :before-upload="beforeUploadSwippers"
            @preview="handlePreview"
            @remove="removeSwipperFile"
          >
            <div v-if="swippersList.length < 6">
              <plus-outlined />
              <div style="margin-top: 8px">选择图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="简介视频" name="video">
          <a-upload
            v-model:file-list="videoList"
            :before-upload="beforeUploadVideo"
            @remove="removeVideoFile"
          >
            <div v-if="videoList.length < 1">
              <a-button>简介视频</a-button>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
      <a-button type="primary" class="submitgBtn" @click="ok">
        确认提交
      </a-button>
    </div>
    <!-- 图片预览 -->
    <a-modal
      :visible="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handleCancel"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </admin-page-template>
</template>

<script setup lang="ts">
import tenMap from "@/components/tenMap.vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import useForm from "@/utils/useForm";
import { reactive, ref, onMounted } from "vue";
import { companyInfoAPi, addCompany, editCompany } from "@/api";
import userStore from "@/store/user";
import { message } from "ant-design-vue";
import config from "@/config";
import { imgToBase64, base64toFile } from "@/utils";

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
const previewVisible = ref(false);
const previewImage = ref("");
const previewTitle = ref("");
const fileList = ref<any[]>([]);
const swippersList = ref<any[]>([]);
const videoList = ref<any[]>([]);
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = "";
};
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};

const beforeUpload = (file: File, files: File[]) => {
  formModel.value.files.push(file);
  console.log(file, files, formModel.value.files);
  return false;
};
const beforeUploadSwippers = (file: File) => {
  formModel.value.swipperFiles.push(file);
  return false;
};

const beforeUploadVideo = (file: File) => {
  formModel.value.video = file;
  console.log(file, formModel.value.video);
  return false;
};

const removeVideoFile = () => {
  videoList.value = [];
  if (formModel.value.video) formModel.value.video = null;
}

const removeFile = (file: File) => {
  formModel.value.files = formModel.value.files.filter(
    // @ts-ignore
    (item: File) => item.uid != file.uid
  );
  if (formModel.value.imgs) {
    formModel.value.imgs = formModel.value.imgs.filter(
      (item: string) => item != file.name
    );
  }
  console.log(file, formModel.value.files, formModel.value.imgs);
};
const removeSwipperFile = (file: File) => {
  formModel.value.swipperFiles = formModel.value.swipperFiles.filter(
    // @ts-ignore
    (item: File) => item.uid != file.uid
  );
  if (formModel.value.swippers) {
    formModel.value.swippers = formModel.value.swippers.filter(
      (item: string) => item != file.name
    );
  }
};

// const companyInfo = ref({});
const getConpamyInfo = () => {
  console.log(userStore.userinfo?.unitId);
  if (userStore.userinfo?.unitId)
    companyInfoAPi(userStore.userinfo?.unitId).then((res) => {
      console.log(res.data.data, Object.prototype.toString.call(res.data.data));
      if (Object.prototype.toString.call(res.data.data) == "[object Object]") {
        res.data.data.lng = Number(res.data.data.lng);
        res.data.data.lat = Number(res.data.data.lat);
        formModel.value = { ...formModel.value, ...res.data.data };
        videoList.value = formModel.value.video ? [{
          uid: Number(new Date()) + formModel.value.video,
          name: formModel.value.video,
          status: "done",
          url: config.baseurl + formModel.value.video,
        }] : []
        fileList.value = formModel.value.imgs
          ? formModel.value.imgs.map((item: string) => {
              // imgToBase64(config.baseurl + item, (base64) => {
              //   formModel.value.files.push(base64toFile(base64, item.split(".")[0]))
              // })
              return {
                uid: Number(new Date()) + item,
                name: item,
                status: "done",
                url: config.baseurl + item,
              };
            })
          : [];
        swippersList.value = formModel.value.swippers
          ? formModel.value.swippers.map((item: string) => {
              // imgToBase64(config.baseurl + item, (base64) => {
              //   formModel.value.files.push(base64toFile(base64, item.split(".")[0]))
              // })
              return {
                uid: Number(new Date()) + item,
                name: item,
                status: "done",
                url: config.baseurl + item,
              };
            })
          : [];
      }
    });
};

onMounted(() => {
  getConpamyInfo();
});

// 获取点位信息
const selectPosition = (position: { lng: string; lat: string }) => {
  console.log("position", position);
  formModel.value.lng = position.lng;
  formModel.value.lat = position.lat;
};

const formObj = reactive({
  addr: undefined,
  addr2: undefined,
  avatar: undefined,
  lng: undefined,
  lat: undefined,
  name: undefined,
  desName: undefined,
  desName1: undefined,
  desName3: undefined,
  video: undefined,
  imgs: [],
  swippers: [],
  swipperFiles: [],
  files: [],
});

const { formref, formModel } = useForm(formObj);

const ok = () => {
  formref.value.validate().then(() => {
    const obj = {
      ...formModel.value,
      unitId: userStore.userinfo?.unitId,
      imgs: JSON.stringify(formModel.value.imgs),
      swippers: formModel.value.swippers?.length > 0 ? JSON.stringify(formModel.value.swippers) : undefined,
    };

    // @ts-ignore
    if (obj.id) {
      editCompany(obj).then(() => {
        message.success("修改成功");
      });
    } else {
      addCompany(obj).then(() => {
        message.success("提交成功");
      });
    }
  });
};
</script>

<style lang="less" scoped>
.companyInfo {
  width: 100%;
  height: 100%;
  background-color: #fff;
  margin-top: 10px;
  padding: 20px 0;
  box-sizing: border-box;
  overflow-y: auto;
  .submitgBtn {
    width: 175px;
    margin-left: 70px;
  }
}
</style>
